<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Wemapr: map-display</title>
<link rel="stylesheet" type="text/css" href="wemapr.css" />
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAjrevdOcDzRtc2JWIyTrRPBROvo4M6CmC77KSRWOC6zqlj8BnFBSna5yp6H9ISXZOSj6vE466qqyY7w"  
type="text/javascript"></script>

<!-- wemapr.s3.aws... key=ABQIAAAAjrevdOcDzRtc2JWIyTrRPBRIm0aEzgz_jKxgCWkUhrc5EfOLVxT32otJCOMcb8tABU03WUPobMjYSg" -->

<script src="ajax.js" type="text/javascript"></script>

<script type="text/javascript" language="javascript">

var map2 = null;
var map_set = 0;
var basicmap;
var mapChoice;  // an array of choice objects
var configFile = "";
var configIdx = 0;
var chartOpacity = 0.5;
var copyrightText = "";
var feedsUrl = null;

function changeOpacity( opacity ){
  chartOpacity = opacity;
  map2.setMapType(G_NORMAL_MAP);
  map2.setMapType(basicmap);
}

function setSearch(){
  configFile = document.getElementById('config').value;
  window.location.search = "?config="+configFile+"&idx="+configIdx;
  return false;
}

function add_choice(choices,index,name,title,map_url,refzoom,centre,zoom,copyright) {
  var sel = document.getElementById('map-select');
  var el = document.createElement('option');
  el.innerHTML = name;
  el.setAttribute("value",index);
  sel.appendChild(el);
  choices.push( new choiceObj(name,title,map_url,refzoom,centre,zoom,copyright));
}


function feed_click(cb){
 //alert("checked =" + cb.checked + " " + cb.value);
 if(cb.checked){
   if(cb.overlay){
     map2.addOverlay(cb.overlay);
   }else{ 
     cb.overlay = new GGeoXml(cb.value, function(){map2.addOverlay(cb.overlay);});
   }
 }else{
   map2.removeOverlay(cb.overlay);
 }
}



function setmap( index ) {
  map_url = mapChoice[index].gmap;
  refzoom = mapChoice[index].refzoom;
  zoom = mapChoice[index].zoom;
  centre = mapChoice[index].centre;
  title =  mapChoice[index].title;
  copyrightText = mapChoice[index].copyright;
  document.getElementById('maptitle').innerHTML=title;
  info_div = document.getElementById('info');
  info_div.appendChild(document.createTextNode( 
    map_url + " zoom=" + zoom));
  info_div.appendChild(document.createElement('br'));

  prefix_el = document.getElementById('prefix1');
  prefix_el.value = map_url;
  if(map2 != null){
    map2.setMapType(G_NORMAL_MAP);
    map2.setMapType(basicmap);
    map2.setZoom(zoom);
    map2.panTo(centre);
  }
}

function choiceObj(name, title, gmap, refzoom, centre, zoom, copyright){
    this.name = name;
    this.title = title;
    this.gmap = gmap;
    this.refzoom = refzoom;
    this.centre = centre;
    this.zoom = zoom;
    this.copyright = copyright;
}


function loadFeeds( feedsList ){
  GDownloadUrl(feedsList, function(data, responseCode) {
     xml=GXml.parse(data);
     feeds = xml.documentElement.getElementsByTagName("feed");
     var div = document.getElementById('feed-menu');
     div.innerHTML="";
     for(i=0;i<feeds.length;i++){
      name=feeds[i].getElementsByTagName("name")[0].childNodes[0].data;
      type=feeds[i].getElementsByTagName("type")[0].childNodes[0].data;
      url=feeds[i].getElementsByTagName("url")[0].childNodes[0].data;
      try{
      icon=feeds[i].getElementsByTagName("icon")[0].childNodes[0].data;
      }catch(e){
      icon=null;
      }
      add_feed( name, type, url, icon);
     }
     var el = document.createElement('br');
     div.appendChild(el);
     //var el = document.createElement('input');
     //el.setAttribute("type","button");
     //el.setAttribute("value","reload feeds");
     //el.setAttribute("onclick","reload_feeds()");
     //div.appendChild(el);
  });
}

function reload_feeds(){
  loadFeeds( feedsUrl );
}

function add_feed( name, type, url, icon ){
  // The way this function adds the checkboxes, mix of DOM and innerHTML, is messy
  // and not inutitive.  It's this way because it kept breaking on either IE7 or
  // Firefox.  This compromise seems to work on both.  I wouldn't do it
  // this way again.

  //var rss2kml = "http://pipes.yahoo.com/pipes/pipe.run?_id=QtW0WlhS3BGeRrmxl7okhQ&_render=kml&feed=";
  var t=new Date().valueOf();
  var stylekml = "http://www.wepoco.com/cgi/wemaprkmlstyle?time="+t+"&kind=kml&style="+icon+"&url=";
  var rss2kml = "http://www.wepoco.com/cgi/wemaprkmlstyle?time="+t+"&kind=rss&style="+icon+"&url=";
  // May as well start loading icon now... 
  if(icon){
    var iconImage = new Image;
    iconImage.src =  "http://maps.google.com/mapfiles/ms/micons/"+icon+".png";
    var im = document.createElement('img');
    im.setAttribute("src",iconImage.src);
    im.setAttribute("height","20");
    im.setAttribute("width","20");
  }
  if(type=="rss"){
    var g_url = rss2kml + encodeURIComponent(url);
  }else{
    var g_url = stylekml + encodeURIComponent(url);
  }
  var div = document.getElementById('feed-menu');
  var eld = document.createElement('div');
  div.appendChild(eld);

  var txtn = document.createElement( 'a' );
  txtn.setAttribute("href",url);
  txtn.innerHTML = name;
  eld.innerHTML = '<input type="checkbox" onclick="feed_click(this)" overlay="" value="'+g_url+'">';
  if(icon){
    eld.appendChild(im);
  }
  eld.appendChild( txtn );
  eld.appendChild(document.createElement('br'));
}

function popupXML( xml ){
  function xmltotxt(str){
    return str.replace(/[<>]/g,function(s){return (s=='<')?'&lt;':'&gt';});
  }
  var xwin = window.open("about:blank");
  var xml_text = new XMLSerializer().serializeToString(xml);
  xwin.document.write('<pre>'+xmltotxt(xml_text)+'</pre>');    
}


function loadxml() {

 var config = document.getElementById('config').value;

 if(config != ""){
 GDownloadUrl(config, function(data, responseCode) {
    mapChoice = new Array();
    var xml = GXml.parse(data);
    
    //popupXML( xml );

    var feeds = xml.documentElement.getElementsByTagName("Feeds");
    for(i=0;i<feeds.length;i++){
      try{
      // feedsUrl is global as may need to reload.
      feedsUrl =  feeds[i].childNodes[0].data;
      loadFeeds(feedsUrl);
      }catch(err){}
    }
    var layers = xml.documentElement.getElementsByTagName("Layer");
    for(i=0;i<layers.length;i++){
      //try{
      var name, title, copyright, centre, zoom, lon, lat, refzoom;
      name=layers[i].getElementsByTagName("name")[0].childNodes[0].data;
      try{
      title=layers[i].getElementsByTagName("title")[0].childNodes[0].data;
      }catch(err){
       title=name;
      }
      try{
      copyright=layers[i].getElementsByTagName("copyright")[0].childNodes[0].data;
      }catch(err){
       copyright="";
      }
      var gmapNode=layers[i].getElementsByTagName("gmap")[0];
      gmap = gmapNode.childNodes[0].data;
      try{
      refzoom = gmapNode.attributes.getNamedItem("max").value;
      }catch(err){
       refzoom=20;  // i.e. no zoom magnify
      }
      try{
      lon=layers[i].getElementsByTagName("lon")[0].childNodes[0].data;
      lat=layers[i].getElementsByTagName("lat")[0].childNodes[0].data;
      centre = new GLatLng(parseFloat(lat),parseFloat(lon));
      }catch(err){
         //alert("lat lon missing");
         centre = new GLatLng(0.0,0.0);
      }

      try{
      zoom = parseInt(layers[i].getElementsByTagName("zoom")[0].childNodes[0].data);
      }catch(err){
         zoom=2
      }
      add_choice( mapChoice, i, name, title, gmap, refzoom, centre, zoom, copyright );
    }
    setmap(configIdx);
 }); //GDownloadUrl
 } //if

}

var missingTiles = new Array;
var emptyImage = new Image;


function isMissingTile(url){
  for(i in missingTiles){
    if(missingTiles[i] == url){
      return 1;
    }
  }
  return 0;
}

// this callback invoked if image tile could not be loaded.
function loadError(){
  if(missingTiles.length > 200){
   missingTiles=missingTiles.slice(0,100);
  }
  missingTiles.unshift(this.src);
}

function testImg( url ){
 if(isMissingTile(url)){
  return emptyImage.src;
 }else{
   // Try to load the image.
   // Failure won't be known until later, but future attempts to load will
   // receive empty tile.
   var im = new Image;
   im.src = url;
   im.onerror = loadError;
   if(im.width != 0){
     return url;
   }
   else{
     var info_div = document.getElementById('info');
     info_div.appendChild(document.createTextNode("missing:" + url));
     info_div.appendChild(document.createElement('br'));
     if(isMissingTile(url)){
       return emptyImage.src;
     }
   }
   return url;
 }
} 

function setup() {

  //window.onbeforeunload=function(){alert("no not again!");};
  chartOpacity = document.getElementById('opacity').value/100.0;
  // Did page open with parameters?
  var searchArr = decodeSearch(window.location);

  for(i in searchArr){
   var ar = searchArr[i].match(/config=(.*)/);
   if(ar){
     configFile = ar[1];
   }
   var idx = searchArr[i].match(/idx=(.*)/);
   if(idx){
     configIdx = idx[1];
   }
  }

  document.getElementById('config').value = configFile;
  loadxml();


  emptyImage.src = "empty.png";
  tabSelect("map");

  map2 = new GMap2(document.getElementById("map-div"));
  map2.addControl(new GLargeMapControl());
  map2.addControl(new GScaleControl());
  map2.enableContinuousZoom();

  var gridlayer = new GTileLayer(new GCopyrightCollection(""),0,12);

  var mapLayer = G_NORMAL_MAP.getTileLayers()[0];
  var basiclayers = [ mapLayer, gridlayer ];

  gridlayer.getTileUrl = function(a,b){
    var prefix = encodeURI(document.getElementById('prefix1').value);
    if(b>refzoom){
      return "http://www.wepoco.com/cgi/wemaprzoom?ref="+refzoom+"&map="+prefix+"&x="+a.x+"&y="+a.y+"&zoom="+b+"&trnsp=0";
    }
    return testImg(prefix+"/"+b+"/"+a.x+"_"+a.y+".png");
  }

  gridlayer.isPng = function() {return 1;}
  gridlayer.getOpacity = function() {return chartOpacity;}
  gridlayer.getCopyright = function(a,b) {
    return { prefix: "&copy;2007", copyrightTexts:[copyrightText]};
  }
  
  basicmap = new GMapType(basiclayers, G_SATELLITE_MAP.getProjection(), 
    "Wemapr", {errorMessage:"Error"});

  map2.addMapType(basicmap);
  map2.setCenter(new GLatLng(0.0, 0.0), 2, G_NORMAL_MAP);

  GEvent.addListener(map2, "click", 
		   function(marker, point) {
		     var info_div = document.getElementById('info');
                     info_div.appendChild(document.createTextNode(
                        point.lat().toFixed(4) + "N " + 
                        point.lng().toFixed(4) + "E"));
                     info_div.appendChild(document.createElement('br'));
                     return;
		   }
  );
  return;
}
</script>

<!-- N.B. .class-style  #id-style -->
<style type="text/css">


#map-sidebar {
   position: absolute;
   left: 690px;
   margin-top: 0px;
   right: 2px;
   height: 450px;
   border: 1px solid black;
}

#map-menu {
}

#map{
   position: absolute;
   margin-left: 0px;
   margin-top: 0px;
   width: 100%;
   height: 550px;
}


#settings {
   z-index: 1;
   position: absolute;
   padding: 20px;
   width: 350px;
   height: 350px;
   background-color: yellow;
}

#tools {
   z-index: 1;
   position: absolute;
   padding: 20px;
   width: 350px;
   height: 350px;
}

#map-div {
   position: absolute;
   margin-left: 4px;
   margin-top: 0px;
   width: 680px;
   height: 450px;
   background-color: gray;
   border: 1px solid black;
}


#info {
   position: absolute;
   overflow: auto;
   margin-left: 10px;
   margin-top: 120px;
   background-color: white;
   width: 305px;
   height: 200px;
   font-family: courier;
   font-size: 10pt;
   color: black;
}


</style>

<script>

var tabbed = new Array( "map", "settings", "tools" );

function _tabClear() {
    var panel,tab;
    for(i in tabbed){
      try{
        panel=document.getElementById(tabbed[i]);
        panel.style.zIndex = -2;
        panel.style.backgroundColor="#ffffaa";
        tab=document.getElementById(tabbed[i]+"-tab");
        tab.style.backgroundColor="#ffffaa";
        tab.style.borderBottom="1px solid black";
      }catch(err){}
    }
}

function tabSelect(name) {
   _tabClear();
   panel=document.getElementById(name);
   panel.style.zIndex=2;
   panel.style.backgroundColor="#ffff00";
   var mytab=document.getElementById(name+"-tab");
   mytab.style.backgroundColor="#ffff00";
   mytab.style.borderBottom="1px solid #ffff00";
}

function tabClick(name) {
  var panel=document.getElementById(name);

  if(panel.style.zIndex < 0){
    _tabClear();
    panel.style.zIndex = 2;
    panel.style.backgroundColor="#ffff00";
    var mytab=document.getElementById(name+"-tab");
    mytab.style.backgroundColor="#ffff00";
    mytab.style.borderBottom="1px solid #ffff00";
  }
}

</script>

</head>
<body onload="setup()" onunload="GUnload()">

<div id="buttonbar" style="position:absolute;" >
  <div class="line" ></div>
  <div id="map-tab" onclick="tabClick('map')" class="tab">&nbsp;map&nbsp;</div>
  <div id="settings-tab" onclick="tabClick('settings')" class="tab">&nbsp;settings&nbsp;</div>
  <div id="tools-tab" onclick="tabClick('tools')" class="tab">&nbsp;tools&nbsp;</div>
</div>

<div style="position:absolute;background:pink;width:100%;height:1px;left:0px;top:20px">



   <div id="map">
      <h2 style="text-align:center" id="maptitle">Wemapr</h2>
      <div id="map-div"></div>
      <div style="position:absolute;bottom:10px;height:20px">
       <table>
       <tbody>
       <tr>
         <td>opacity</td>
         <td><select id="opacity"onchange="changeOpacity(this.value/100.0)">
         <option selected value="25">25%</option>
         <option value="50">50%</option>
         <option value="75">75%</option>
         </select></td>
       </tr>
       </tbody>
       </table>
      </div>
     <div id="map-sidebar">
       <form>
       <div id="map-menu">
         <select id="map-select" onchange="setmap(this.value)" name="map-select">
         <!-- <option value="null">---</option> -->
         </select>
         <input type="button" value="chart info" onclick="chartInfo()" />
       </div>
       <div id="feed-menu"></div>
       </form>
     </div>
   </div>
   <div id="settings" >
       <div>
       <!-- <form onsubmit="setSearch()"> -->
       <input type="hidden" id="base" value="" />
       <input type="hidden" id="prefix1" value="" />
       <input type="hidden" id="prefix0" value="" />
       <table>
       <tbody>
       <tr>
       <td>file</td>
       <td>
         <input type="text" id="config" onchange="setSearch()" />
       </td>
       <td>
         <input type="button" value="load" onclick="setSearch()" />
       </td>
       </tr>
       </tbody>
       </table>
       <!-- </form> -->
       </div>
       <div id="info"></div>
    </div> 
    <div id="tools" >
      <p><a href="map-define.html">Import charts</a></p>
    </div>
   </div>
</body>
</html>
